package JUC.第05章_中断机制_LockSupport;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class B1_synchronized介绍 {
    public static void main(String[] args) {

        Object lock = new Object();
        Thread a = new Thread(()->{
            synchronized (lock){
                System.out.println("进入->" + Thread.currentThread().getName());
                try {
                    //wait的时候，会释放锁，可以让别人抢到
                    lock.wait();//必须在自己的 锁块里
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " 被唤醒->");

            }
        },"a");

        a.start();
        try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}

        Thread b = new Thread(()->{
            synchronized (lock){
                System.out.println("进入->" + Thread.currentThread().getName());
                //唤醒后，会使锁可以再次被获取
                lock.notify();//必须在自己的 锁块里,而且必须在 wait 之后
                System.out.println(Thread.currentThread().getName() + " 唤醒->" + a.getName());
                try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}
            }
        },"b");

        b.start();

    }
}
